package tutorial.example1;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import com.thoughtworks.xstream.XStream;

public class XStreamExample {
	private XStream m_xstream;
	
	public XStreamExample() {
		m_xstream = new XStream();
		//Tao alias cho XStream
		m_xstream.alias("person", Person.class);
		m_xstream.alias("phonenumber", PhoneNumber.class);
	}
	
	/**	
	* Phan giai tuan tu doi tuong thanh XML	
	*/	
	public void writeXML() {	
		Person joe = new Person("Joe", "Walnes");	
		joe.setPhone(new PhoneNumber(123, "1234-456"));	
		joe.setFax(new PhoneNumber(123, "9999-999"));	
		// Phan giai tuan tu doi tuong thanh XML	
		String xml = m_xstream.toXML(joe);
		System.out.println(xml);	
	}	
	
	/**	
	* Phan giai doi tuong thanh XML. Ghi xuong tap tin	
	*/	
	public void writeXML1() {	
		Person joe = new Person("Joe", "Walnes");	
		joe.setPhone(new PhoneNumber(123, "1234-456"));	
		joe.setFax(new PhoneNumber(123, "9999-999"));	
		try {
			FileOutputStream fos = new FileOutputStream("test.xml");	
			OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");	
			//Ghi pha`n da`u cua tap tin xml va encoding caa no la UTF-8	
			osw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n\n");	
			m_xstream.toXML(joe, osw);	
			osw.close();	
			fos.close();	
		} catch (FileNotFoundException e) {		
			e.printStackTrace();		
		} catch (IOException e) {		
			e.printStackTrace();		
		}	
	}
	
	/**	
	* Doc tu tap tin XML thanh doi tuong.	
	*/	
	public void readXML() {	
		try {
			FileInputStream fis = new FileInputStream("test.xml");	
			InputStreamReader fsr = new InputStreamReader(fis);
			Person newJoe = (Person) m_xstream.fromXML(fsr);
			System.out.println(newJoe.getFirstname());	
			System.out.println(newJoe.getLastname());	
			System.out.println("Phone number " +	
			newJoe.getPhone().getNumber());	
			System.out.println("Fax number " +	
			newJoe.getFax().getNumber());	
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	/**	
	* @param args	
	*/	
	public static void main(String[] args) {	
		XStreamExample test = new XStreamExample();		
		// test.writeXML1();		
		test.writeXML();		
		// test.readXML();	
	}
}